package lv.dysnomia.server.entities;

import java.util.{List=>JavaList};

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import lv.dysnomia.portal.web.PMF;

object LilypondDAO {

  def getLilypondByLabel(label: String): Lilypond = {
    val emptyLilypond = new Lilypond
    val pm = PMF.getInstance.getPersistenceManager
    val lilypond: Lilypond = try {
      val query: Query = pm.newQuery((new Lilypond).getClass)
      query.setFilter("label == labelParam")
      query.declareParameters("String labelParam")
      val results: JavaList[Lilypond] = query.execute(label).asInstanceOf[JavaList[Lilypond]]
      if (results != null && results.size() > 0) results.get(0)
      else emptyLilypond
    } catch {
      case e: Exception => { println(e.toString); emptyLilypond }
    }
    finally {
      pm.close();
    }
    return lilypond
  }

  def getSongs(): JavaList[Lilypond] = {
    val pm = PMF.getInstance.getPersistenceManager
    val lilyponds: JavaList[Lilypond] = try {
      val query = pm.newQuery((new Lilypond).getClass)
      val result = query.execute.asInstanceOf[JavaList[Lilypond]]
      result.size; result
    } catch {
      case e: Exception => { println(e.toString); Nil.asInstanceOf[JavaList[Lilypond]] }
    }
    finally {
      pm.close();
    }
    return lilyponds
  }
  

  def save(l: Lilypond): Unit = {
    val pm = PMF.getInstance.getPersistenceManager
    try {
      pm.makePersistent(l)
    } finally {
      pm.close()
    }
  }

  def removeByLabel(label: String): Long = {
    val pm = PMF.getInstance.getPersistenceManager
    try {
      val query = pm.newQuery((new Lilypond).getClass)
      query.setFilter("label == labelParam")
      query.declareParameters("String labelParam")
      query.deletePersistentAll(label)
    } finally {
      pm.close()
    }
  }

  def removeAll(): Long = {
    val pm = PMF.getInstance.getPersistenceManager
    try {
      val query = pm.newQuery((new Lilypond).getClass)
      query.deletePersistentAll()
    } finally {
      pm.close()
    }
  }
}
